import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sinosheets/network/api/resource_api.dart';
import 'package:sinosheets/utils/common_utils/log_util.dart';
import 'package:sinosheets/utils/language/en.dart';
import 'package:sinosheets/utils/language/isar_lang_service.dart';
import 'package:sinosheets/utils/language/zh.dart';
import 'package:sinosheets/utils/language/language_isolate.dart';

class TranslationService extends Translations {
  static const fallbackLocale = Locale('en', 'US');
  static Locale? get locale => const Locale('en', 'US');

  final Map<String, Map<String, String>> _cache = {};

  @override
  Map<String, Map<String, String>> get keys => _cache;

  /// 初始化本地语言存储并加载到内存中
  Future<void> init() async {
    _cache['en'] = en_language;
    _cache['zh'] = zh_language;

    await getLangFromLocal();
    // await updateLanguagesFromRemote();
  }

  ///从本地数据库获取语言 然后合并到_cache（用isolate合并）
  Future<void> getLangFromLocal() async {
    final isar = IsarLangService();
    await isar.init();
    final enLang = await isar.getLangMap('en');
    final zhLang = await isar.getLangMap('zh');
    // isolate合并
    _cache['en'] = await mergeLanguageMapInIsolate(local: _cache['en'] ?? {}, remote: enLang);
    _cache['zh'] = await mergeLanguageMapInIsolate(local: _cache['zh'] ?? {}, remote: zhLang);
    // 可选：刷新当前 UI 的语言
    final current = Get.locale?.languageCode ?? 'en';
    Get.updateLocale(Locale(current));
  }

  /// 根据远程接口更新语言（可在启动后调用，isolate合并）
  Future<void> updateLanguagesFromRemote() async {
    try {
      final response = await ResourceApis.getLangResult();

      if (response.isSuccess && response.data != null) {
        final remoteLangMap = response.data['langMap'];
        final isar = IsarLangService();

        if (remoteLangMap != null && remoteLangMap is Map<String, dynamic>) {
          for (final entry in remoteLangMap.entries) {
            final locale = entry.key;
            final remoteMapRaw = entry.value;

            if (remoteMapRaw is Map<String, dynamic>) {
              // 获取本地已有语言（如果没有则为空 map）
              final localMap = await isar.getLangMap(locale);

              // isolate合并，远程优先
              final mergedMap = await mergeLanguageMapInIsolate(
                local: localMap,
                remote: remoteMapRaw,
              );

              // 缓存并保存到数据库
              _cache[locale] = await mergeLanguageMapInIsolate(local: _cache[locale] ?? {}, remote: mergedMap);
              await isar.saveLangMap(locale, mergedMap);
            }
          }

          // 可选：刷新当前 UI 的语言
          final current = Get.locale?.languageCode ?? 'en';
          Get.updateLocale(Locale(current));
        }
      } else {
        LogUtil.e('[TranslationService] 接口失败: [${response.code}]');
      }
    } catch (e) {
      LogUtil.e('[TranslationService] 更新语言失败: $e');
    }
  }
}
